<?php

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose 
 */
use \GatewayWorker\Lib\Gateway;

require_once 'vendor/Connection.php';
require_once 'vendor/redis.php';
require_once 'controller/controller.php';

//数据驱动

class Events {

    public static $db;
    public static $redis;
    public static $controller;

    //与start_gateway 只能一处生效
    public static function onWorkerStart($businessWorker) {
        // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
        static::$db = new \Workerman\MySQL\Connection('47.98.198.195', '3306', 'work_chat', 'work_chat', 'work_chat');
        //实例话redis链接
        $config = array('master' => array('ip' => '47.98.198.195', 'host' => 9000));
        //实例话 静态redis
        static::$redis = new redis_connnect($config['master'], 'heyiwei');
        //实例话 常用公用方法
        static::$controller = new controller(static::$db, static::$redis);
    }

    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
     */
    public static function onMessage($client_id, $message) {
//        print_r($message);
        // 客户端传递的是json数据 不是json的再见
        $message_data = json_decode($message, true);
        if (empty($message_data) || empty($message_data['type'])) {
            //给单人发送 
            $rs['status'] = 'false';
            $rs['msg'] = '发送的数据格式有误';
            Gateway::sendToClient($client_id, json_encode($rs));
            //断开单人的链接  测试阶段 不要打开
            //Gateway::closeClient($client_id);
            return;
        }
        // 根据类型执行不同的业务
        switch ($message_data['type']) {
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'ping':
                //接受心跳 
                return;
            case 'login':
                //账号密码判断 sendToClient
                if (empty($message_data['name']) || empty($message_data['pwd'])) {
                    $rs['status'] = 'false';
                    $rs['msg'] = '请输入账号或密码';
                    Gateway::sendToClient($client_id, json_encode($rs));
                    return;
                }
                $uid = static::$controller->check_login($message_data['name'], $message_data['pwd']);
                if (!$uid) {
                    $rs['status'] = 'false';
                    $rs['msg'] = '账号密码错误';
                    Gateway::sendToClient($client_id, json_encode($rs));
                    return;
                } else {
                    $encode_key = static::$controller->pbulic_encode($uid);
                    //验证token存到redis用于后续验证  2小时到期
                    $savetoken = static::$redis->set(md5($uid), $encode_key, 7200);
                    if (!$savetoken) {
                        $rs['status'] = 'false';
                        $rs['msg'] = '请重试';
                        Gateway::sendToClient($client_id, json_encode($rs));
                        return;
                    }
                    //验证通过生成一串加密字符串用于验证
                    $rs['status'] = 'true';
                    $rs['uid'] = md5($uid);
                    $rs['msg'] = $encode_key;
                    Gateway::sendToClient($client_id, json_encode($rs));
                    return;
                }
            case 'join_room':
                $token = $message_data['token'];
                $uid = $message_data['uid'];
                if (empty($token) || empty($uid)) {
                    //不带token的一律直接抛弃
                    $rs_msg['status'] = 'false';
                    $rs_msg['error'] = 101;
                    $rs_msg['msg'] = '不带token的一律直接抛弃';
                    Gateway::sendToClient($client_id, json_encode($rs_msg));
                    return;
                }
                //检测登录token错误的滚蛋
                $check_login = static::$controller->check_token($uid, $token);
                if ($check_login != TRUE) {
                    $rs_msg['status'] = 'false';
                    $rs_msg['error'] = 102;
                    $rs_msg['msg'] = 'token验证失败,或者压根就没有';
                    Gateway::sendToClient($client_id, json_encode($rs_msg));
                    return;
                }
                //当前只开2个房间
                if (!in_array($message_data['room_id'], array(1, 2))) {
                    $rs_msg['type'] = 'login';
                    $rs_msg['status'] = 'fasle';
                    $rs_msg['msg'] = 'must be used Room number';
                    Gateway::sendToClient($client_id, json_encode($rs_msg));
                    return;
                }
                //绑定用户id与用户的client_id  绑定后后面直接使用 $uid 发送信息
                Gateway::bindUid($client_id, $uid);
                // 把房间号昵称放到session中
                $room_id = $message_data['room_id'];
                $client_name = htmlspecialchars($message_data['client_name']);
                //操作当前用户session
                $_SESSION['room_id'] = $room_id;
                $_SESSION['client_name'] = $client_name;
                // 获取当前分组里面所有用户列表 
                $clients_list = Gateway::getClientSessionsByGroup($room_id);
                foreach ($clients_list as $tmp_client_id => $item) {
                    $clients_list[$tmp_client_id] = $item['client_name'];
                }
                $clients_list[$client_id] = $client_name;
                // 转播给当前房间的所有客户端，xx进入聊天室 message {type:login, client_id:xx, name:xx} 
                $new_message = array('type' => $message_data['type'], 'client_id' => $client_id, 'client_name' => htmlspecialchars($client_name), 'time' => date('Y-m-d H:i:s'));
                Gateway::sendToGroup($room_id, json_encode($new_message));
                Gateway::joinGroup($client_id, $room_id);

                // 给当前用户发送用户列表  sendToCurrentClient(只能给当前用户发) =  sendToClient （只要有id都能打）
                $new_message['client_list'] = $clients_list;
                print_r($new_message);
                Gateway::sendToCurrentClient(json_encode($new_message));
                return;

            // 客户端发言 message: {type:say, to_client_id:xx, content:xx}
            case 'say':
                // 非法请求
                if (!isset($_SESSION['room_id'])) {
                    //给单人发送 
                    $rs['msg'] = '没有房间号,必须带房间号';
                    Gateway::sendToClient($client_id, json_encode($rs));
                    return;
                }
                $room_id = $_SESSION['room_id'];
                $client_name = $_SESSION['client_name'];

                // 私聊
                if ($message_data['to_client_id'] != 'all') {
                    $new_message = array(
                        'type' => 'say',
                        'from_client_id' => $client_id,
                        'from_client_name' => $client_name,
                        'to_client_id' => $message_data['to_client_id'],
                        'content' => "<b>对你说: </b>" . nl2br(htmlspecialchars($message_data['content'])),
                        'time' => date('Y-m-d H:i:s'),
                    );
                    Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message));
                    $new_message['content'] = "<b>你对" . htmlspecialchars($message_data['to_client_name']) . "说: </b>" . nl2br(htmlspecialchars($message_data['content']));
                    return Gateway::sendToCurrentClient(json_encode($new_message));
                }
                $new_message = array(
                    'type' => 'say',
                    'from_client_id' => $client_id,
                    'from_client_name' => $client_name,
                    'to_client_id' => 'all',
                    'content' => nl2br(htmlspecialchars($message_data['content'])),
                    'time' => date('Y-m-d H:i:s'),
                );
                return Gateway::sendToGroup($room_id, json_encode($new_message));
            default :
                //不带类型的统统滚蛋
                $rs['msg'] = '你先干啥';
                Gateway::sendToClient($client_id, json_encode($rs));
                //断开单人的链接
//                Gateway::closeClient($client_id);
                break;
        }
    }

    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id) {
        // debug
//        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
        echo "{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']}" . date('H-i-s', time()) . " is lose \n";
        // 从房间的客户端列表中删除
        if (isset($_SESSION['room_id'])) {
            $room_id = $_SESSION['room_id'];
            $new_message = array('type' => 'logout', 'from_client_id' => $client_id, 'from_client_name' => $_SESSION['client_name'], 'time' => date('Y-m-d H:i:s'));
            Gateway::sendToGroup($room_id, json_encode($new_message));
        }
    }

    //回复信息
    public static function send_msg($client_id = '', $status = '-1', $data = '') {
        $msg['status'] = $status;
        $msg['data'] = $data;
        $msg['msg'] = '';
        if ($status == -1) {
            $msg['data'] = '';
            $msg['msg'] = $data;
        }
        Gateway::sendToClient($client_id, json_encode($msg));
    }

}
